<template>
  <div>
    <el-alert
      title="警告提示"
      type="warning"
      description="如遇会议室状态为异常不可进行会议预约，请悉知！！！"
      :closable="false"
      show-icon>
    </el-alert>
    <el-tabs v-model="activeName" >
      <el-tab-pane label="会议室申请" name="first">
        <el-row>
          <el-col :span="8" v-for="item in table.tableData" :key="item.id" style="padding-right: 10px; padding-bottom: 10px; cursor: pointer">
            <el-card :body-style="{ padding: '10px' }" shadow="hover">
              <img :src="downloadApi+item.img" alt="培训图片" class="training-image"  />
              <div style="padding: 10px">
                <span>{{ item.roomName }}</span>
                <div class="bottom clearfix">
                  <span style="font-size: 14px">
                  备注信息：<span style="color: #409EFF">{{ item.remark }}</span>
                  </span>
                </div>
                <div class="bottom clearfix">
                <span style="font-size: 14px">
                  会议室状态
                  <el-tag v-if="item.status === 0" type="danger">异常</el-tag>
                  <el-tag v-else-if="item.status === 1" type="success">正常</el-tag>
                </span>
                </div>
                <div class="bottom clearfix">
                <span style="font-size: 14px">
                  可容纳人数
                </span>
                  <el-tag>{{ item.num }}</el-tag>
                  <el-button type="danger" class="sta-button" @click="openDialog(item)">报修</el-button>
                  <el-button type="primary" class="sta-button" :disabled="item.status === 0" @click="openDrawer(item)">预约</el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
        <el-drawer :before-close="handleClose" :visible.sync="drawer" custom-class="demo-drawer"
                   ref="drawer" :size="drawerWidth" :show-close="false">
          <div class="demo-drawer__content">
            <el-form ref="form" :model="form" label-width="120px" :rules="form.rules">
              <el-form-item label="会议名称" prop="title">
                <el-input v-model="form.title" style="width: 60%"></el-input>
              </el-form-item>
              <el-form-item label="会议备注" prop="remark">
                <el-input type="textarea" v-model="form.remark" style="width: 60%"></el-input>
              </el-form-item>
              <el-form-item label="会议日期" prop="meetingDate">
                <el-date-picker v-model="form.meetingDate" :pickerOptions="pickerOptions"/>
              </el-form-item>
              <el-form-item label="会议开始时间" prop="startTime">
                <el-time-select
                  v-model="form.startTime"
                  placeholder="选择会议开始时间"
                  :picker-options="startPickerOptions"
                  @change="updateEndTimeOptions">
                </el-time-select>
              </el-form-item>
              <el-form-item label="会议结束时间" prop="endTime">
                <el-select v-model="form.endTime" placeholder="选择会议结束时间" clearable >
                  <el-option
                    v-for="option in endOptions"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="参会部门" prop="deptId">
                <el-select v-model="form.deptId" style="width: 60%" >
                  <el-option
                    v-for="item in optionList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <div class="demo-drawer__footer">
              <el-button @click="cancelForm">取 消</el-button>
              <el-button type="primary" @click="submitForm">确 定</el-button>
            </div>
          </div>
        </el-drawer>
      </el-tab-pane>
      <el-tab-pane label="我的会议申请" name="second">
        <div class="common-table">
          <el-table :data="table1.tableData" border height="600px" stripe row-key="id"
                    :header-cell-style="{ background: '#eef1f6',color: '#606266',textAlign:'center',fontWeight:'bold',borderWidth:'3px'}">
            <el-table-column prop="roomName" label="会议室名称" min-width="125"/>
            <el-table-column prop="title" label="会议名称" min-width="125"/>
            <el-table-column prop="remark" label="会议简介" min-width="125"/>
            <el-table-column prop="createTime" label="申请时间" min-width="150"/>
            <el-table-column label="审核状态" min-width="50px">
              <template slot-scope="scope">
                <el-tag :type="approveForm.tagType[scope.row.status]">
                  {{scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="60px">
              <template slot-scope="scope">
                <el-button v-if="scope.row.status==='未审核'" size="mini" type="primary" @click="cancel(scope.row)">撤销</el-button>
                <el-button v-if="scope.row.status!=='未审核'" size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            style="margin-top: 10px;float: right"
            layout="total,sizes,prev,pager,next,jumper"
            :page-size="table1.pageConfig.size ? table1.pageConfig.size : 10"
            :page-sizes="[5, 10, 15, 20]"
            :total="table1.pageConfig.total"
            :current-page.sync="table1.pageConfig.current"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          ></el-pagination>
        </div>
      </el-tab-pane>
      <el-tab-pane label="我的报修申请" name="third">
        <div class="common-table">
          <el-table :data="table2.tableData" border height="600px" stripe row-key="id"
                    :header-cell-style="{ background: '#eef1f6',color: '#606266',textAlign:'center',fontWeight:'bold',borderWidth:'3px'}">
            <el-table-column prop="roomName" label="会议室名称" min-width="125"/>
            <el-table-column prop="remark" label="报修说明" min-width="200" />
            <el-table-column prop="createTime" label="申请时间" width="170"/>
            <el-table-column label="审核状态" min-width="50px">
              <template slot-scope="scope">
                <el-tag :type="approveForm.tagType[scope.row.status]">
                  {{scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="60px">
              <template slot-scope="scope">
                <el-button v-if="scope.row.status==='未审核'" size="mini" type="primary" @click="cancel(scope.row)">撤销</el-button>
                <el-button v-if="scope.row.status!=='未审核'" size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            style="margin-top: 10px;float: right"
            layout="total,sizes,prev,pager,next,jumper"
            :page-size="table2.pageConfig.size ? table2.pageConfig.size : 10"
            :page-sizes="[5, 10, 15, 20]"
            :total="table2.pageConfig.total"
            :current-page.sync="table2.pageConfig.current"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          ></el-pagination>
        </div>
      </el-tab-pane>
    </el-tabs>
    <el-dialog title="会议室报修" :visible.sync="dialogFormVisible" :before-close="handleClose" width="30%">
      <el-form :model="RepairForm" :rules="RepairForm.rules" ref="RepairForm">
        <el-form-item label="报修原因" :label-width="formLabelWidth" prop="remark">
          <el-input v-model="RepairForm.remark" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="SetRepair">确 定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import {getList} from "../../../api/room";
import {getDownloadApi} from "../../../api/docs";
import {add} from "../../../api/staffRoom";
import {getListByStaffId} from "../../../api/staffRoom";
import {deleteOne, edit as editLeave} from "../../../api/staffRoom";
import {getAllDept} from "../../../api/dept";
import {addRepair, getListRepair} from "../../../api/roomRepair";

export default {
  data() {
    return {
      dialogFormVisible: false,
      optionList: {},
      drawerWidth: '40%',
      drawer: false,
      direction: 'rtl',
      staff: JSON.parse(localStorage.getItem("staff")),
      formLabelWidth: '80px',
      table: {
        tableData: [],
        pageConfig: {
          total: 10, // 记录总数
          current: 1, // 起始页
          size: 10 // 每页展示的记录数
        }
      },
      table1: {
        tableData: [],
        pageConfig: {
          total: 10, // 记录总数
          current: 1, // 起始页
          size: 10 // 每页展示的记录数
        }
      },
      table2: {
        tableData: [],
        pageConfig: {
          total: 10, // 记录总数
          current: 1, // 起始页
          size: 10 // 每页展示的记录数
        }
      },
      activeName: 'first',
      form: {
        startTime: '',
        endTime: '',
        staffId: '',
        roomId: '',
        deptId: '',
        rules: {
          title: [
            { required: true, message: '请输入会议标题', trigger: 'blur'},
          ],
          remark: [
            { required: true, message: '请输入会议简介', trigger: 'blur'},
          ],
          deptId: [
            { required: true, message: '请选择参会部门', trigger: 'blur' }
          ],
          startTime: [
            { required: true, message: '请选择会议开始时间', trigger: 'blur' }
          ],
          endTime: [
            { required: true, message: '请选择会议结束时间', trigger: 'blur' }
          ],
          meetingDate: [
            { required: true, message: '请选择会议日期', trigger: 'blur'}
          ]
        },
      },
      RepairForm: {
        staffId: '',
        roomId: '',
        remark: '',
        rules: {
          remark: [
            { required: true, message: '请输入报修问题', trigger: 'blur'},
          ]
        }
      },
      pickerOptions: {
        // 不能选择今天之前的日期
        disabledDate(time) {
          // 计算一周后的时间
          const oneWeekLater = new Date();
          oneWeekLater.setDate(oneWeekLater.getDate() + 7);
          // 禁用一周之外的日期
          return time.getTime() < Date.now() || time.getTime() > oneWeekLater.getTime();
          // return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
        }
      },
      approveForm: {
        tagType: {
          "未审核": "info",
          "审核通过": "success",
          "驳回": "danger",
          "撤销": "warning"
        }
      },
      startPickerOptions: { // 会议开始时间选择器的设置
        disabledHours: function() {
          return [0, 1, 2, 3, 4, 5, 6, 7, 18, 19, 20, 21, 22, 23]; // 禁用的小时段
        },
        disabledMinutes: function(hour) {
          if (hour === 8) { // 如果选择了早上8点，则禁用8:00之前的分钟
            return Array.from({ length: 30 }, function(_, i) { return i; });
          } else {
            return [];
          }
        }
      },
      endOptions: [] // 存储会议结束时间选项
    };
  },
  created() {
    this.loading()
  },
  computed: {
    downloadApi() {
      return getDownloadApi()
    },
  },
  methods: {
    updateEndTimeOptions() {
      // 获取选择的会议日期
      const meetingDate = this.form.meetingDate;
      // 获取选择的会议开始时间
      const startTime = this.form.startTime;
      // 添加额外的错误检查
      if (!meetingDate || !startTime) {
        return;
      }
      // 获取会议日期的年、月和日
      const year = meetingDate.getFullYear();
      const month = meetingDate.getMonth();
      const day = meetingDate.getDate();
      // 解析会议日期和开始时间，并构造完整的日期时间对象
      const [hours, minutes] = startTime.split(':').map(Number);
      const startDateTime = new Date(year, month, day, hours, minutes);
      // 检查日期对象是否有效
      if (isNaN(startDateTime)) {
        return;
      }
      const endTimeOptions = [];
      // 如果开始时间不为空
      if (startTime) {
        // 构造最早结束时间对象
        const earliestEndTime = new Date(year, month, day, hours, minutes);
        // 计算最早结束时间
        earliestEndTime.setMinutes(earliestEndTime.getMinutes() + 30);
        // 添加可选时间到结束时间选项数组
        while (earliestEndTime <= new Date(year, month, day, 18, 0)) {
          endTimeOptions.push({
            label: this.formatTime(earliestEndTime),
            // 创建一个新的日期对象以避免引用问题
            value: this.formatTime(earliestEndTime),
            // value: new Date(earliestEndTime)
          });
          earliestEndTime.setMinutes(earliestEndTime.getMinutes() + 30);
        }
      }
      this.endOptions = endTimeOptions;
      console.log(this.endOptions)
      // 仅在结束时间不为空时重置为最早时间
      if (!this.form.endTime) {
        this.form.endTime = this.endOptions.length > 0 ? this.endOptions[0].value : '';
      }
    },
    formatTime(time) {
      return new Date(time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    },
    getDept() {
      // 将optionList定义为数组
      this.optionList = [];
      getAllDept().then(response => {
        // 遍历部门列表
        response.data.forEach(dept => {
          // 检查部门是否有子部门
          if (dept.children.length > 0) {
            // 使用 push 方法将子部门数据添加到数组中
            this.optionList.push(...dept.children);
          }
        });
        // 输出包含所有子部门数据的数组
      });
    },
    openDrawer(item) {
      this.drawer = true
      this.MeetingId = item.id
      this.getDept()
    },
    openDialog(item) {
      this.dialogFormVisible = true
      this.MeetingRoomId = item.id
      console.log(this.MeetingRoomId)
    },
    SetRepair() {
      this.$refs.RepairForm.validate(valid => {
        if (valid) {
          this.RepairForm.roomId = this.MeetingRoomId
          this.RepairForm.staffId = this.staff.id
          addRepair(this.RepairForm).then(response => {
            if (response.code === 200) {
              this.$message.success("报修信息提交成功！")
              this.dialogFormVisible = false
              this.RepairForm.remark = ''
              this.loading()
            } else {
              this.$message.error("报修信息提交失败")
            }
          })
        } else {
          return false
        }
      })
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    loading() {
      getList({
        current: this.table.pageConfig.current,
        size: this.table.pageConfig.size,
      }, this.formData).then(response => {
        if (response.code === 200) {
          this.table.tableData = response.data.list
          this.table.pageConfig.total = response.data.total
        } else {
          this.$message.error(response.message)
        }
      })

      getListRepair({
        current: this.table2.pageConfig.current,
        size: this.table2.pageConfig.size,
      }, this.formData).then(response => {
        if (response.code === 200) {
          this.table2.tableData = response.data.list
          this.table2.pageConfig.total = response.data.total
        } else {
          this.$message.error(response.message)
        }
      })

      getListByStaffId({
        current: this.table1.pageConfig.current,
        size: this.table1.pageConfig.size,
        id: this.staff.id
      }).then(response => {
        if (response.code === 200) {
          this.table1.tableData = response.data.list
          this.table1.pageConfig.total = response.data.total
        } else {
          this.$message.error(response.message)
        }
      })
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.form.roomId = this.MeetingId
          this.form.staffId = this.staff.id
          add(this.form).then(response => {
            if (response.code === 200) {
              this.$message.success("提交成功！")
              this.drawer = false;
              this.form = ''
              this.loading()
            } else {
              this.$message.error("提交失败")
            }
          })
        } else {
          return false
        }
      })
    },
    cancelForm() {
      this.drawer = false;
    },
    handleDelete(row) {
      deleteOne(row.id).then(response => {
        if (response.code === 200) {
          this.loading()
          this.$message.success("删除成功")
        } else {
          this.$message.error("删除失败")
        }
      })
    },
    cancel(row) {
      editLeave({id: row.id, status: '撤销'}).then(response => {
        if (response.code === 200) {
          this.loading()
          this.$message.success("撤销成功")
        } else {
          this.$message.error("撤销失败")
        }
      })
    },
    handleSizeChange(size) {
      this.table.pageConfig.size = size
      this.loading()
    },
    handleCurrentChange(current) {
      this.table.pageConfig.current = current
      this.loading()
    },
  }
};
</script>

<style>
.bottom {
  margin-top: 10px;
  line-height: 12px;
}

.sta-button {
  float: right;
  margin: 5px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.training-image {
  max-width: 100%;
  max-height: 200px;
}

.demo-drawer__footer {
  margin-left: 20px;
}

.el-drawer__header {
  padding: 0 !important;
  margin-bottom: 10px !important;
}
</style>
